<template>
  <UploadExcel :on-success="success" />
</template>

<script>
import { importEmployee } from '@/api/employees'
export default {
  data() {
    return {
      type: this.$router.query
    }
  },
  methods: {
    async success({ header, results }) {
      console.log(header)
      console.log(results)
      if (this.type === 'user') {
        const dictionary = { // 查询字典
          '入职日期': 'timeOfEntry',
          '手机号': 'mobile',
          '姓名': 'username',
          '转正日期': 'correctionTime',
          '工号': 'workNumber'
        }
        const data = results.map(item => {
        // console.log(item)
          const res = this.cnToEn(item, dictionary)
          console.log(res)
          return res
        })
        await importEmployee(data)
        this.$message('导入成功')
      }
      this.$router.back()
    },
    cnToEn(item, dictionary) {
      const newItem = {}
      for (const key in item) {
        const newKey = dictionary[key]
        let value = item[key]
        if (newKey === 'timeOfEntry' || newKey === 'correctionTime') {
          // 注意需要变为日期对象 才能入库
          const formatedDateStr = this.formatDate(value, '/')
          value = new Date(formatedDateStr)
        }
        newItem[newKey] = value
      }
      return newItem
    },
    // 转换时间
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style>

</style>
